﻿#Region "Copyright (C) 2005-2011 Team MediaPortal"

' Copyright (C) 2005-2011 Team MediaPortal
' http://www.team-mediaportal.com
' 
' MediaPortal is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 2 of the License, or
' (at your option) any later version.
' 
' MediaPortal is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU General Public License for more details.
' 
' You should have received a copy of the GNU General Public License
' along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.

#End Region

Imports System.ServiceProcess
Imports System.Threading

Public Class Install

#Region "Members"


    'Registry Keys für MediaPortal
    Private Const _virtualStoreRegSubKey32b As String = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MediaPortal TV Server"
    Private Const _virtualStoreRegSubKey64b As String = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\MediaPortal TV Server"

#End Region

#Region "Static properties"

    ''' <summary>
    ''' TvServerPath lesen
    ''' </summary>
    ''' <returns>TvServerPath</returns>
    Public ReadOnly Property TvServerpath() As String
        Get
            If OS.GetOSType = OS.OSType.Is32Bit Then
                Return (My.Computer.Registry.GetValue(_virtualStoreRegSubKey32b, "InstallPath", Nothing).ToString & "\")
            ElseIf OS.GetOSType = OS.OSType.Is64Bit Then
                Return (My.Computer.Registry.GetValue(_virtualStoreRegSubKey64b, "InstallPath", Nothing).ToString & "\")
            Else
                Return String.Empty
            End If
        End Get
    End Property

    ''' <summary>
    ''' Prüfen ob TvService läuft
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    Public ReadOnly Property TvServiceIsRunning() As Boolean
        Get
            'Prüfen ob TvService läuft
            Dim Service As ServiceController = New ServiceController("TVService")
            Return CBool(Service.Status = ServiceProcess.ServiceControllerStatus.Running)
            Service.Close()
        End Get
    End Property
#End Region

#Region "Form settings"
    Private Sub btInstall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btInstall.Click

        LBInfo.Items.Clear()

        Dim InstallProcess As New Thread(AddressOf Install)
        InstallProcess.Start()

    End Sub
    Private Sub Install_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadFormSettings()
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        End
    End Sub

    Private Sub LoadFormSettings()
        If String.IsNullOrEmpty(TvServerpath) Then
            LBInfo.Items.Add("MediaPortal TvServer path not found!")
            btInstall.Enabled = False

        Else
            LBInfo.Items.Add("MediaPortal TvServer path found:")
            LBInfo.Items.Add(TvServerpath)
            btInstall.Enabled = True
        End If

        Try
            If TvServiceIsRunning = True Then
                LTvServiceStatus.Text = "TvService is running"
                LTvServiceStatus.BackColor = Color.Green
            End If
        Catch ex As Exception
            LTvServiceStatus.Text = "TvService not running"
            LTvServiceStatus.BackColor = Color.Red
        End Try

        LBInfo.Items.Add("")
        LBInfo.Items.Add("Press the install button to start TvServer Plugin installation.")

    End Sub

#End Region

#Region "Install"
    Private Sub Install()
        If TvServiceIsRunning = True Then
            'TvService Läuft

            Dim _resultMSG As String
            _resultMSG = MsgBox("TvService is running!" & vbNewLine & _
                                "The TvService have to stop, before installation." & vbNewLine & _
                                "Check if any records are in progress" & vbNewLine & vbNewLine & _
                                "Stop the TvServer ?", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, "Attention")

            If _resultMSG = vbYes Then
                'TvService stoppen nach abfrage
                LBInfo.Items.Add("Stop TvService...")
                Try
                    'TvService stoppen + warten bis Dateisystem verfügbar
                    Dim _TvService As New System.ServiceProcess.ServiceController("TVService")
                    _TvService.Stop()
                    _TvService.WaitForStatus(ServiceControllerStatus.Stopped)
                    Thread.Sleep(30000)
                    LBInfo.Items.Add("TvService successfully stopped...")
                    CopyFiles()
                Catch ex As Exception
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            Else
                MsgBox("You must stop the TvServer before installing!", MsgBoxStyle.Critical, "Information")
                LoadFormSettings()
                Exit Sub
            End If

        Else
            'TvService Läuft nicht
            CopyFiles()
        End If

        LBInfo.Items.Add("Start TvService...")

        Try
            Dim _TvService As New System.ServiceProcess.ServiceController("TVService")
            _TvService.Start()
            _TvService.WaitForStatus(ServiceControllerStatus.Running)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        Try
            If TvServiceIsRunning = True Then
                LTvServiceStatus.Text = "TvService is running"
                LTvServiceStatus.BackColor = Color.Green
            Else
                LTvServiceStatus.Text = "TvService not running"
                LTvServiceStatus.BackColor = Color.Red
            End If
        Catch ex As Exception
            LTvServiceStatus.Text = "TvService not running"
            LTvServiceStatus.BackColor = Color.Red
        End Try

        LBInfo.Items.Add("TvService successfully started...")
        LBInfo.Items.Add("")
        LBInfo.Items.Add("TvMovie++ Plugin successfully installed!")

        MsgBox("TvMovie++ Plugin successfully installed!", MsgBoxStyle.Information)
        End
    End Sub
    Private Sub CopyFiles()
        Try
            Try
                If TvServiceIsRunning = True Then
                    LTvServiceStatus.Text = "TvService is running"
                    LTvServiceStatus.BackColor = Color.Green
                Else
                    LTvServiceStatus.Text = "TvService not running"
                    LTvServiceStatus.BackColor = Color.Red
                End If
            Catch ex As Exception
                LTvServiceStatus.Text = "TvService not running"
                LTvServiceStatus.BackColor = Color.Red
            End Try

            LBInfo.Items.Add("")

            'TvServer Files löschen & kopieren
            For Each file As String In IO.Directory.GetFiles(Application.StartupPath & "\Tvserver")

                If My.Computer.FileSystem.FileExists(file) = True Then
                    Dim _FileName = IO.Path.GetFileName(file)

                    If My.Computer.FileSystem.FileExists(TvServerpath & _FileName) = True Then
                        My.Computer.FileSystem.DeleteFile(TvServerpath & _FileName, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.ThrowException)
                    End If

                    IO.File.Copy(file, TvServerpath & _FileName, True)  ' Kopiert die Dateien
                    LBInfo.Items.Add("Copy file: " & _FileName)
                End If

            Next

            'Plugins löschen & kopieren
            For Each file As String In IO.Directory.GetFiles(Application.StartupPath & "\Tvserver\Plugins")

                If My.Computer.FileSystem.FileExists(file) = True Then
                    Dim _FileName = IO.Path.GetFileName(file)

                    If My.Computer.FileSystem.FileExists(TvServerpath & "Plugins\" & _FileName) = True Then
                        My.Computer.FileSystem.DeleteFile(TvServerpath & "Plugins\" & _FileName, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.ThrowException)
                    End If

                    IO.File.Copy(file, TvServerpath & "Plugins\" & _FileName, True)  ' Kopiert die Dateien
                    LBInfo.Items.Add("Copy file: \\Plugins\" & _FileName)
                End If

            Next

            LBInfo.Items.Add("")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
#End Region


End Class

#Region "32/64bit check"
Public Class OS
    Public Enum OSType
        Is32Bit
        Is64Bit
    End Enum

    ''' <summary>
    ''' Gibt den Typ des Betriebssystems zurück (32 oder 64 Bit)
    ''' </summary>
    <System.ComponentModel.Description("Gibt den Typ des Betriebssystems zurück, also 32 oder 64 Bit")> _
    Public Shared Function GetOSType() As OSType
        Return IIf(IntPtr.Size = 4, OS.OSType.Is32Bit, OS.OSType.Is64Bit)
    End Function
End Class
#End Region